<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <el-form inline :model="queryParams" class="mb-3">
            <el-form-item label="患者姓名">
                <el-input 
                    v-model="queryParams.userName" 
                    placeholder="请输入患者姓名" 
                    clearable 
                    style="width: 200px"
                    @keyup.enter.native="handleQuery"
                ></el-input>
            </el-form-item>
            <el-form-item label="预约时间">
                <el-date-picker 
                    v-model="dateRange" 
                    type="datetimerange" 
                    range-separator="至" 
                    start-placeholder="开始时间"
                    end-placeholder="结束时间" 
                    value-format="yyyy-MM-dd HH:mm:ss" 
                    unlink-panels
                ></el-date-picker>
            </el-form-item>
            <el-form-item label="通知类型">
                <el-select 
                    v-model="queryParams.noticeSubtype" 
                    placeholder="请选择通知类型" 
                    clearable 
                    style="width: 200px"
                >
                    <el-option 
                        v-for="dict in dict.type.notice_appointment_subtype" 
                        :key="dict.dictValue" 
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form>

        <!-- 预约通知列表 -->
        <el-table 
            :data="tableData" 
            border 
            v-loading="loading" 
            style="width: 100%" 
            @row-click="handleRowClick"
        >
            <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
            <el-table-column prop="title" label="通知标题" align="center"></el-table-column>
            <el-table-column prop="userName" label="患者姓名" align="center"></el-table-column>
            <el-table-column prop="appointmentTime" label="预约时间" align="center">
                <template slot-scope="scope">{{ parseTime(scope.row.appointmentTime) }}</template>
            </el-table-column>
            <el-table-column label="通知类型" align="center">
                <template slot-scope="scope">
                    {{ selectDictLabel(dict.type.notice_appointment_subtype, scope.row.noticeSubtype) }}
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center" width="100">
                <template slot-scope="scope">
                    <el-tag type="danger" v-if="scope.row.isRead === 0">未读</el-tag>
                    <el-tag type="success" v-else>已读</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="发送时间" align="center">
                <template slot-scope="scope">{{ parseTime(scope.row.createTime) }}</template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180">
                <template slot-scope="scope">
                    <el-button 
                        v-if="scope.row.isRead === 0" 
                        type="text" 
                        size="small"
                        @click="handleMarkRead(scope.row.noticeId, $event)"
                    >
                        标记已读
                    </el-button>
                    <el-button 
                        type="text" 
                        size="small" 
                        @click="handleViewDetail(scope.row, $event)"
                    >
                        查看详情
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination 
            @size-change="handleSizeChange" 
            @current-change="handleCurrentChange"
            :current-page="queryParams.pageNum" 
            :page-sizes="[10, 20, 30, 50]" 
            :page-size="queryParams.pageSize"
            :total="total" 
            layout="total, sizes, prev, pager, next, jumper" 
            class="mt-3"
        ></el-pagination>

        <!-- 详情弹窗 -->
        <el-dialog 
            title="预约通知详情" 
            :visible.sync="detailVisible" 
            width="60%" 
            :close-on-click-modal="false"
        >
            <el-descriptions border>
                <el-descriptions-item label="通知标题">{{ detail.title }}</el-descriptions-item>
                <el-descriptions-item label="通知类型">
                    {{ selectDictLabel(dict.type.notice_appointment_subtype, detail.noticeSubtype) }}
                </el-descriptions-item>
                <el-descriptions-item label="患者姓名" v-if="detail.userName">
                    {{ detail.userName }}
                </el-descriptions-item>
                <el-descriptions-item label="预约时间" v-if="detail.appointmentTime">
                    {{ parseTime(detail.appointmentTime) }}
                </el-descriptions-item>
                <el-descriptions-item label="发送时间">
                    {{ parseTime(detail.createTime) }}
                </el-descriptions-item>
                <el-descriptions-item label="通知内容" :span="3">
                    <div style="white-space: pre-line;">{{ detail.content }}</div>
                </el-descriptions-item>
            </el-descriptions>
            <div slot="footer" class="dialog-footer">
                <el-button @click="detailVisible = false">关闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getNoticeList, markNoticeRead, getUnreadCount } from '../../api/notice/notice'

export default {
    name: 'AppointmentNotice',
    dicts: ['notice_appointment_subtype'],
    data() {
        return {
            tableData: [],
            total: 0,
            loading: false,
            queryParams: {
                noticeType: 0, 
                pageNum: 1,
                pageSize: 10,
                userName: '',
                noticeSubtype: null,
                startTime: null,
                endTime: null
            },
            dateRange: [],
            detailVisible: false,
            detail: {}
        }
    },
    created() {
        this.loadNoticeData()
        this.loadUnreadCount()
    },
    methods: {

        loadNoticeData() {
            this.loading = true
            if (this.dateRange && this.dateRange.length === 2) {
                this.queryParams.startTime = this.dateRange[0]
                this.queryParams.endTime = this.dateRange[1]
            } else {
                this.queryParams.startTime = null
                this.queryParams.endTime = null
            }
            getNoticeList(this.queryParams).then(response => {
                this.tableData = response.rows || []
                this.total = response.total || 0
                this.loading = false
            }).catch(error => {
                this.loading = false
                this.$message.error('加载预约通知失败：' + (error.message || '未知错误'))
            })
        },

        //查询按钮
        handleQuery() {
            this.queryParams.pageNum = 1
            this.loadNoticeData()
        },

        //重置按钮
        handleReset() {
            this.queryParams.userName = ''
            this.queryParams.noticeSubtype = null
            this.dateRange = []
            this.queryParams.startTime = null
            this.queryParams.endTime = null
            this.handleQuery()
        },

        //分页方法
        handleSizeChange(size) {
            this.queryParams.pageSize = size
            this.loadNoticeData()
        },
        handleCurrentChange(page) {
            this.queryParams.pageNum = page
            this.loadNoticeData()
        },

        // 标记已读
        handleMarkRead(noticeId, event) {
            if (event) event.stopPropagation()
            this.$confirm('确定标记为已读吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'info'
            }).then(() => {
                markNoticeRead(noticeId).then(() => {
                    this.$message.success('标记成功')
                    this.loadNoticeData()
                }).catch(error => {
                    this.$message.error('标记失败：' + (error.message || '操作失败'))
                })
            })
        },

        // 查看详情
        handleViewDetail(row, event) {
            if (event) event.stopPropagation()
            this.detail = { ...row }
            this.detailVisible = true
            if (row.isRead === 0) {
                this.handleMarkRead(row.noticeId)
            }
        },

        // 行点击查看详情
        handleRowClick(row) {
            this.handleViewDetail(row)
        },

        // 加载未读数量
        loadUnreadCount() {
            getUnreadCount(0).then(response => {
                const unreadCount = response.data || 0
                if (this.$store && this.$store.dispatch) {
                    this.$store.dispatch('tagsView/updateVisitedView', {
                        path: this.$route.path,
                        meta: { title: `预约通知${unreadCount > 0 ? '(' + unreadCount + ')' : ''}` }
                    }).catch(() => {})
                }
            }).catch(error => {
                console.error('获取预约通知未读数量失败：', error)
            })
        }
    }
}
</script>

<style scoped>
.app-container {
    padding: 20px;
}
.dialog-footer {
    text-align: center;
}
</style>